#include "delay.h"
#include "stm32f10x.h"
void tim6_init(uint16_t prescaler)
{
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6,ENABLE);
	
	//TIM_TimeBaseInitStruct.TIM_ClockDivision=TIM_CKD_DIV1;   //tim6不存在ckd域不需要配置
	TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up;
	TIM_TimeBaseInitStruct.TIM_Period=0;
	TIM_TimeBaseInitStruct.TIM_Prescaler=prescaler;
	
	
	//时基单元初始化
	//void TIM_TimeBaseInit(TIM_TypeDef* TIMx, TIM_TimeBaseInitTypeDef* TIM_TimeBaseInitStruct);
	TIM_TimeBaseInit(TIM6,&TIM_TimeBaseInitStruct);
	
}


void tim6_delay(uint16_t count)
{
	//设置自动重装载值
	//void TIM_SetAutoreload(TIM_TypeDef* TIMx, uint16_t Autoreload);
	TIM_SetAutoreload(TIM6,count);

	//手动软件清除标志
	//void TIM_ClearFlag(TIM_TypeDef* TIMx, uint16_t TIM_FLAG);
	TIM_ClearFlag(TIM6,TIM_FLAG_Update);
	
	//使能定时器
	//void TIM_Cmd(TIM_TypeDef* TIMx, FunctionalState NewState);
	TIM_Cmd(TIM6,ENABLE);
	
	//等待更新标志
	//FlagStatus TIM_GetFlagStatus(TIM_TypeDef* TIMx, uint16_t TIM_FLAG);
	while(TIM_GetFlagStatus(TIM6,TIM_FLAG_Update)!=SET);
	
	TIM_Cmd(TIM6,DISABLE);
}

void tim6_delay_us(uint16_t us)
{
	//ÉèÖÃ×°ÔØÖµ
	TIM6->ARR=us;
	//Çå³ý¸üÐÂ±êÖ¾
	TIM6->SR = (uint16_t)~TIM_FLAG_Update;
	//Ê¹ÄÜ¼ÆÊýÆ÷
	TIM6->CR1 |= TIM_CR1_CEN;
	//µÈ´ý¼ÆÊýÍê³É
	while(TIM_GetFlagStatus(TIM6,TIM_FLAG_Update)==RESET);
	//¹Ø±Õ¼ÆÊýÆ÷
	TIM6->CR1 &= (uint16_t)(~((uint16_t)TIM_CR1_CEN));
}

void tim6_delay_ms(int ms)
{
	int i;
	for (i=0;i<ms;i++)
	{
		tim6_delay_us(1000);
	}
}
